'''
  Convert DrawingBoard .draw format to simple .svg file
'''

svg_base_template = '''<?xml version="1.0" encoding="utf-8"?>
<svg width="100%%" height="100%%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
%(frames)s
</defs>
<use xlink:href="#frame001" x="0" y="0" id="drawingBoard">
    <animate attributeName="xlink:href" values="%(frame_ids)s" attributeType="XML" dur="%(playing_time)ss" begin="drawingBoard.load" repeatCount="1"/>
</use>
</svg>'''

svg_frame_template = '''<svg width="100%%" height="100%%" id="frame%(frameno)s">
%(line_data)s
</svg>'''

svg_line_template = '''<path fill="white" stroke-width="%(width)d" stroke="%(color)s" stroke-linejoin="round" stroke-linecap="round" d="%(path)s"/>'''

class SVGWriter(object):

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self._lines = []
        self._curr_line = None
        self._pencolor = None
        self._penwidth = None
        self._frames = []
        
    def __str__(self):
        # finish and close structures
        self._close_frame()
        frames = ''.join(self._frames)
        frame_ids = ';'.join(['#frame%03d' % (i + 1) for i in range(len(self._frames))])
        playing_time = 0.2 * len(self._frames)
        # build and return string value
        return svg_base_template % locals()
        
    def DrawingBoardVersion(self, version):
        pass
        
    def frame(self):
        self._close_frame()
        self._curr_line = None
        self._lines = []
        
    def pen_color(self, *color):
        self._pencolor = self._svgcolor(*color)
        self._curr_line = None
        
    def _svgcolor(self, r, g, b, a):
        'ignores alpha'
        return 'rgb(%d%%, %d%%, %d%%)' % (r * 100, g * 100, b * 100)
        
    def pen_width(self, width):
        self._penwidth = width
        self._curr_line = None
        
    def move_to(self, x, y):
        if not self._curr_line:
           self._curr_line = [self._pencolor, self._penwidth]
           self._lines.append(self._curr_line)
        self._curr_line.append('M%s %s' % (x, self.height - y))
        self._inLineTo = False
        
    def line_to(self, x, y):
        self._curr_line.append('L%s %s' % (x, self.height - y))
        
    def _format_line(self, line):
        color, width = line[:2]
        path = ' '.join(line[2:])
        return svg_line_template % locals()
        
    def _close_frame(self):
        if not self._lines: return
        frameno = '%03d' % (len(self._frames) + 1)
        line_data = ''.join([self._format_line(line) for line in self._lines])
        frame = svg_frame_template % locals()
        self._frames.append(frame)
        self._lines = []
        self._curr_line = None
        
        
        
